<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
      <div>
        <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">
          {{ $t('auth.registerTitle') }}
        </h2>
        <p class="mt-2 text-center text-sm text-gray-600">
          {{ $t('auth.hasAccount') }}
          <router-link
            to="/login"
            class="font-medium text-primary-600 hover:text-primary-500"
          >
            {{ $t('auth.loginNow') }}
          </router-link>
        </p>
      </div>

      <form class="mt-8 space-y-6" @submit.prevent="handleRegister">
        <div class="space-y-4">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700">
              {{ $t('auth.username') }}
            </label>
            <input
              id="username"
              v-model="form.username"
              name="username"
              type="text"
              required
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
              :placeholder="$t('auth.placeholders.username')"
            />
          </div>

          <div>
            <label for="email" class="block text-sm font-medium text-gray-700">
              {{ $t('auth.email') }}
            </label>
            <input
              id="email"
              v-model="form.email"
              name="email"
              type="email"
              autocomplete="email"
              required
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
              :placeholder="$t('auth.placeholders.email')"
            />
          </div>

          <div>
            <label for="verification_code" class="block text-sm font-medium text-gray-700">
              邮箱验证码
            </label>
            <div class="mt-1 flex space-x-2">
              <input
                id="verification_code"
                v-model="form.verification_code"
                name="verification_code"
                type="text"
                maxlength="6"
                required
                class="flex-1 appearance-none relative block px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
                placeholder="请输入6位验证码"
              />
              <button
                type="button"
                @click="sendVerificationCodeHandler"
                :disabled="!canSendCode || sendingCode"
                class="px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                {{ sendingCode ? '发送中...' : (countdown > 0 ? `${countdown}s` : '发送验证码') }}
              </button>
            </div>
          </div>

          <div>
            <label for="phone" class="block text-sm font-medium text-gray-700">
              {{ $t('auth.phoneOptional') }}
            </label>
            <input
              id="phone"
              v-model="form.phone_number"
              name="phone"
              type="tel"
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
              :placeholder="$t('auth.placeholders.phone')"
            />
          </div>

          <div>
            <label for="password" class="block text-sm font-medium text-gray-700">
              {{ $t('auth.password') }}
            </label>
            <input
              id="password"
              v-model="form.password"
              name="password"
              type="password"
              autocomplete="new-password"
              required
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
              :placeholder="$t('auth.placeholders.password')"
            />
          </div>

          <div>
            <label for="confirmPassword" class="block text-sm font-medium text-gray-700">
              {{ $t('auth.confirmPassword') }}
            </label>
            <input
              id="confirmPassword"
              v-model="confirmPassword"
              name="confirmPassword"
              type="password"
              autocomplete="new-password"
              required
              class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
              :placeholder="$t('auth.placeholders.confirmPassword')"
            />
          </div>
        </div>

        <div class="flex items-center">
          <input
            id="agree-terms"
            v-model="agreeTerms"
            name="agree-terms"
            type="checkbox"
            required
            class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
          />
          <label for="agree-terms" class="ml-2 block text-sm text-gray-900">
            {{ $t('auth.agreeTerms') }}
          </label>
        </div>

        <!-- 错误提示 -->
        <div v-if="authStore.error || validationError" class="rounded-md bg-red-50 p-4">
          <div class="flex">
            <div class="flex-shrink-0">
              <ExclamationTriangleIcon class="h-5 w-5 text-red-400" />
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-red-800">
                {{ authStore.error || validationError }}
              </h3>
            </div>
          </div>
        </div>

        <div>
          <button
            type="submit"
            :disabled="authStore.isLoading"
            class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <span v-if="authStore.isLoading" class="absolute left-0 inset-y-0 flex items-center pl-3">
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
            </span>
            {{ authStore.isLoading ? $t('common.loading') : $t('auth.registerButton') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { useAuthStore } from '@/stores/auth'
import { isValidEmail, isValidPhone } from '@/utils/helpers'
import { sendVerificationCode } from '@/api/emailVerification'

const router = useRouter()
const authStore = useAuthStore()

// 表单数据
const form = ref({
  username: '',
  email: '',
  password: '',
  phone_number: '',
  verification_code: '',
})

const confirmPassword = ref('')
const agreeTerms = ref(false)

// 验证码相关状态
const sendingCode = ref(false)
const countdown = ref(0)
let countdownTimer: number | null = null

// 计算是否可以发送验证码
const canSendCode = computed(() => {
  return form.value.email && isValidEmail(form.value.email) && countdown.value === 0
})

// 验证错误
const validationError = computed(() => {
  if (!form.value.username.trim()) {
    return ''
  }

  if (!form.value.email.trim()) {
    return ''
  }

  if (form.value.email && !isValidEmail(form.value.email)) {
    return '请输入有效的邮箱地址'
  }

  if (form.value.phone_number && !isValidPhone(form.value.phone_number)) {
    return '请输入有效的香港手机号码'
  }

  if (!form.value.password) {
    return ''
  }

  if (form.value.password.length < 6) {
    return '密码至少需要6个字符'
  }

  if (form.value.password !== confirmPassword.value) {
    return '两次输入的密码不一致'
  }

  if (!agreeTerms.value) {
    return '请同意服务条款和隐私政策'
  }

  return ''
})

// 处理注册
const handleRegister = async () => {
  // 清除之前的错误
  authStore.clearError()

  // 验证表单
  if (validationError.value) {
    return
  }

  // 基础验证
  if (!form.value.username || !form.value.email || !form.value.password) {
    return
  }

  const registerData = {
    username: form.value.username.trim(),
    email: form.value.email.trim(),
    password: form.value.password,
    phone_number: form.value.phone_number.trim() || undefined,
    verification_code: form.value.verification_code.trim(),
  }

  const success = await authStore.register(registerData)

  if (success) {
    // 注册成功，跳转到首页
    router.push('/')
  }
}

// 发送验证码
const sendVerificationCodeHandler = async () => {
  if (!form.value.email || !isValidEmail(form.value.email)) {
    alert('请输入有效的邮箱地址')
    return
  }

  try {
    sendingCode.value = true
    await sendVerificationCode({
      email: form.value.email,
      type: 'register'
    })

    alert('验证码已发送，请查收邮件')

    // 开始倒计时
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer!)
        countdownTimer = null
      }
    }, 1000)
  } catch (error: any) {
    alert(error.response?.data?.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}

onMounted(() => {
  // 清除之前的错误
  authStore.clearError()
})

onUnmounted(() => {
  // 清理倒计时器
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>
